﻿var UserSubmit, GeneralSubmit, ContactInfoSubmit, AppearanceSubmit, CultureSubmit, FamilySubmit, LivingSubmit;
var editUserAction, editGeneralAction, editContactInfoAction, editAppearanceAction, editCultureAction, editFamilyAction, editLivingAction;

var UserActive;
var UserVerify;
var UserDisable;

var ResetPassword;

var DeleteReport;

var showHideEdit;

var ChangeEmailListType;
var SendMailSuccess;

var UpdateSuccess = "Cập nhật thành công";
var UpdateFail = "Lỗi hệ thống";
var SearchFieldRequired = "Vui lòng nhập từ khóa";

var filterResult;

$(document).ready(function() {

    // set lại ids cho tabs
    $(document.body).tabs({
        idtab: '#tab-nav-profile > ul > li > a',
        idtarget: '#tab-nav-profile-target .tab-target'
    });

    showHideEdit = function(show, hide) {
        $(hide).css("display", "none");
        $(show).css("display", "block");
    };

    Shadowbox.init({
        players: ["html", "iframe"],
        overlayOpacity: 0.4,
        handleOversize: "resize"
    });

    /*** begin: User ***/

    UserSubmit = function() {

        var status = $("#opt-User-Status").val();
        var userKey = $("#hid-UserKey").val();
        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: 'edituser',
                userkey: userKey,
                status: status
            },
            success: function(data) {
                editUserAction(data);
            }
        });
    };

    editUserAction = function(data) {
        if (data.result == '1') {
            alert(UpdateSuccess);
            $("#span-User-Status").html($("#opt-User-Status :selected").text());
            showHideEdit('#Show-User', '#Edit-User');
        }
        else {
            alert(UpdateFail);
        }
    };

    /*** end: User ***/

    /*** begin: UserGeneralProfile ***/
    GeneralSubmit = function() {

        if ($("#txt-General-Name").val() == "") {
            return;
        }

        if ($("#txt-General-BirthDate").val() == "") {
            return;
        }

        if ($("#chk-General-LookingFor-Male").is(':checked') == false
            && $("#chk-General-LookingFor-Female").is(':checked') == false) {
            return;
        }

        var userKey = $("#hid-UserKey").val();
        var name = $("#txt-General-Name").val();
        var gender = $("#opt-General-Gender").val();
        var birthDate = $("#txt-General-BirthDate").val();
        var city = $("#opt-General-City").val();
        var education = $("#opt-General-Education").val();
        var job = $("#opt-General-Job").val();
        var hobby = $("#txt-General-Hobby").val();
        var blast = $("#txt-General-Blast").val();

        var lookingFor;
        if ($("#chk-General-LookingFor-Male").is(':checked') == true
            && $("#chk-General-LookingFor-Female").is(':checked') == true) {
            lookingFor = 2;
        }
        else {
            if ($("#chk-General-LookingFor-Male").is(':checked') == true) {
                lookingFor = 1;
            }

            if ($("#chk-General-LookingFor-Female").is(':checked') == true) {
                lookingFor = 0;
            }
        }

        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: 'editgeneral',
                userkey: userKey,
                name: name,
                gender: gender,
                birthdate: birthDate,
                city: city,
                education: education,
                job: job,
                lookingFor: lookingFor,
                hobby: hobby,
                blast: blast
            },
            success: function(data) {
                editGeneralAction(data);
            }
        });
    };

    editGeneralAction = function(data) {
        if (data.result == '1') {
            alert(UpdateSuccess);
            $("#span-General-Name").html($("#txt-General-Name").val());
            $("#span-General-Gender").html($("#opt-General-Gender :selected").text());
            $("#span-General-BirthDate").html($("#txt-General-BirthDate").val());
            $("#span-General-City").html($("#opt-General-City :selected").text());
            $("#span-ContactInfo-City").html($("#opt-General-City :selected").text());
            $("#span-General-Education").html($("#opt-General-Education :selected").text());
            $("#span-General-Job").html($("#opt-General-Job :selected").text());
            $("#span-General-Hobby").html($("#txt-General-Hobby").val());
            if ($("#chk-General-LookingFor-Male").is(':checked') == true
            && $("#chk-General-LookingFor-Female").is(':checked') == true) {
                $("#span-General-LookingFor").html("Nam và Nữ");
            }
            else {
                if ($("#chk-General-LookingFor-Male").is(':checked') == true) {
                    $("#span-General-LookingFor").html("Nam");
                }

                if ($("#chk-General-LookingFor-Female").is(':checked') == true) {
                    $("#span-General-LookingFor").html("Nữ");
                }
            }
            $("#span-General-Blast").html($("#txt-General-Blast").val());

            showHideEdit('#Show-General', '#Edit-General');
        }
        else {
            alert(UpdateFail);
        }
    };

    /*** end: UserGeneralProfile ***/

    /*** begin: UserContactInfo ***/

    ContactInfoSubmit = function() {
    };

    editContactInfoAction = function(data) {
    };

    /*** end: UserContactInfo ***/

    /*** begin: UserAppearanceProfile ***/

    AppearanceSubmit = function() {
        if ($("#txt-Appearance-Height").val() == "") {
            return;
        }

        if ($("#txt-Appearance-Weight").val() == "") {
            return;
        }

        var userKey = $("#hid-UserKey").val();
        var height = $("#txt-Appearance-Height").val();
        var weight = $("#txt-Appearance-Weight").val();

        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: 'editappearance',
                userkey: userKey,
                height: height,
                weight: weight
            },
            success: function(data) {
                editAppearanceAction(data);
            }
        });
    };

    editAppearanceAction = function(data) {
        if (data.result == '1') {
            alert(UpdateSuccess);
            $("#span-Appearance-Height").html($("#txt-Appearance-Height").val());
            $("#span-Appearance-Weight").html($("#txt-Appearance-Weight").val());

            showHideEdit('#Show-Appearance', '#Edit-Appearance');
        }
        else {
            alert(UpdateFail);
        }
    };

    /*** end: UserAppearanceProfile ***/

    /*** begin: UserCultureProfile ***/

    CultureSubmit = function() {
        var userKey = $("#hid-UserKey").val();
        var religion = $("#opt-Culture-Religion").val();

        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: 'editculture',
                userkey: userKey,
                religion: religion
            },
            success: function(data) {
                editCultureAction(data);
            }
        });
    };

    editCultureAction = function(data) {
        if (data.result == '1') {
            alert(UpdateSuccess);
            $("#span-Culture-Religion").html($("#opt-Culture-Religion :selected").text());

            showHideEdit('#Show-Culture', '#Edit-Culture');
        }
        else {
            alert(UpdateFail);
        }
    };

    /*** end: UserCultureProfile ***/

    /*** begin: UserFamilyProfile ***/

    FamilySubmit = function() {
        var userKey = $("#hid-UserKey").val();
        var maritalStatus = $("#opt-Family-MaritalStatus").val();

        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: 'editfamily',
                userkey: userKey,
                maritalstatus: maritalStatus
            },
            success: function(data) {
                editFamilyAction(data);
            }
        });
    };

    editFamilyAction = function(data) {
        if (data.result == '1') {
            alert(UpdateSuccess);
            $("#span-Family-MaritalStatus").html($("#opt-Family-MaritalStatus :selected").text());

            showHideEdit('#Show-Family', '#Edit-Family');
        }
        else {
            alert(UpdateFail);
        }
    };

    /*** end: UserFamilyProfile ***/

    /*** begin: UserLivingProfile ***/

    LivingSubmit = function() {
        var userKey = $("#hid-UserKey").val();
        var smoking = $("#opt-Living-Smoking").val();
        var income = $("#txt-Living-Income").val();

        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: 'editliving',
                userkey: userKey,
                smoking: smoking,
                income: income
            },
            success: function(data) {
                editLivingAction(data);
            }
        });
    };

    editLivingAction = function(data) {
        if (data.result == '1') {
            alert(UpdateSuccess);
            $("#span-Living-Smoking").html($("#opt-Living-Smoking :selected").text());
            $("#span-Living-Income").html($("#txt-Living-Income").val());

            showHideEdit('#Show-Living', '#Edit-Living');
        }
        else {
            alert(UpdateFail);
        }
    };

    /*** end: UserLivingProfile ***/

    /*** begin: Active User ***/

    UserActive = function(userKey) {
        var action;
        if ($("#chkActive-" + userKey).is(":checked")) {
            action = "activeUser";
        }
        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: action,
                userkey: userKey
            },
            success: function(data) {
                if (data.result == '0') {
                    alert(UpdateFail);
                    return;
                }
                $("#chkActive-" + userKey).attr("disabled", "disabled");
                $("#chkVerify-" + userKey).removeAttr("disabled");
                $("#chkDisable-" + userKey).removeAttr("disabled");
            }
        });
    };

    /*** begin: Verify User ***/

    UserVerify = function(userKey) {
        var action;
        if ($("#chkVerify-" + userKey).is(":checked")) {
            action = "verifyUser";
        }
        else {
            action = "unVerifyUser";
        }
        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: action,
                userkey: userKey
            },
            success: function(data) {
                if (data.result == '0') {
                    alert(UpdateFail);
                }
            }
        });
    };

    /*** begin: Disable User ***/

    UserDisable = function(userKey) {
        var action;
        if ($("#chkDisable-" + userKey).is(":checked")) {
            action = "disableUser";
        }
        else {
            action = "unDisableUser";
        }
        $.ajax({
            async: true,
            dataType: 'json',
            url: "../../api/users/user.ashx",
            type: 'POST',
            data: {
                action: action,
                userkey: userKey
            },
            success: function(data) {
                if (data.result == '0') {
                    alert(UpdateFail);
                }
            }
        });
    };

    /*** begin: Reset Password ***/

    ResetPassword = function(userKey) {
        jConfirm('Xác nhận reset mật khẩu?', 'Xác nhận', function(r) {
            if (r) {
                $.ajax({
                    async: false,
                    dataType: 'json',
                    url: "/api/users/user.ashx",
                    type: 'POST',
                    data: {
                        action: "resetPassword",
                        userKey: userKey
                    },
                    success: function(data) {
                        if (data.result == "0") {
                            jAlert(UpdateFail);
                            return;
                        }
                        jAlert("Mật khẩu mới: " + data.newPass);
                    }
                });
            }
        });
    };

    /*** begin: Paging ***/

    $('#txtCurrentPage').keypress(function(event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            $("#btnGo").click();
        }
    });

    $("#btnGo").click(function() {
        var url;
        url = $("#TargetPage").val() + "?";
        url += $("#QueryString").val();
        url += "page=" + $("#txtCurrentPage").val();
        window.parent.location = url;
    });

    /*** begin: End Paging ***/

    /*** begin: User List ***/

    $("#btnFilter").click(function() {
        var url;
        url = "/users/danh_sach?";
        url += "gioitinh=" + $("#optGenderFilter :selected").val();
        url += "&trangthai=" + $("#optStatusFilter :selected").val();
        if ($("#chkHaveAvatar").is(":checked")) {
            url += "&avatar=true";
        }
        window.parent.location = url;
    });

    /*** end: User List ***/

    /*** begin: User Search ***/

    $("#btnSearch").click(function() {
        if ($("#txtSearchField").val() == "") {
            alert(SearchFieldRequired);
            return;
        }
        var url;
        url = "/users/tim_kiem?";
        url += "tukhoa=" + $("#txtSearchField").val().replace(/%/g, "%25");
        url += "&timtheo=" + $("#optSearchBy :selected").val();
        window.location = url;
    });
    /*** end: User Search ***/

    /*** begin: User Report ***/

    DeleteReport = function(reportID, reportedUserKey) {
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/users/user.ashx",
            type: 'POST',
            data: {
                action: "deleteReport",
                reportID: reportID,
                reportedUserKey: reportedUserKey
            },
            success: function(data) {
                if (data.result == "0") {
                    jAlert(UpdateFail);
                    return;
                }
                $("#chkSetRead-" + reportID).attr("checked", "checked");
                $("#chkSetRead-" + reportID).attr("disabled", "disabled");
            }
        });
    };

    /*** end: User Report ***/

    /*** begin: Send Mail ***/

    ChangeEmailListType = function() {
        if ($("#rdList").is(":checked")) {
            $("#ListEmail").removeAttr("disabled");
            $("#FileEmail").attr("disabled", "disabled");
        }
        else {
            $("#FileEmail").removeAttr("disabled");
            $("#ListEmail").attr("disabled", "disabled");
        }
    };

    $("#btnPreview").click(function() {
        if ($("#txtTitle").val() == "") {
            jAlert("Vui lòng nhập tiêu đề thư");
            return;
        }
        if ($("#MailEditor_ifr").contents().find("#tinymce").html() == '<p><br _mce_bogus="1"></p>') {
            jAlert("Vui lòng nhập nội dung thư");
            return;
        }
        var refesh = new Date();
        var content = $("#MailEditor_ifr").contents().find("#tinymce").html();
        content = content.replace(/</g, "|lt");
        content = content.replace(/>/g, "|gt");

        $("#txtContent").val(content);
        $("#action-request").attr("name", "temp");
        $("#aspnetForm").attr("action", GLOBAL_ROOT_URL + "users/mailpreview?" + refesh.getMilliseconds());
        $("#aspnetForm").attr("method", "post");
        $("#aspnetForm").attr("target", "_blank");
        $("#aspnetForm").submit();
    });

    $("#btnSubmitMail").click(function() {
        if ($("#txtTitle").val() == "") {
            jAlert("Vui lòng nhập tiêu đề thư");
            return;
        }
        if ($("#MailEditor_ifr").contents().find("#tinymce").html() == '<p><br _mce_bogus="1"></p>') {
            jAlert("Vui lòng nhập nội dung thư");
            return;
        }
        if ($("#rdList").is(":checked")) {
            if ($("#ListEmail").val() == "") {
                jAlert("Vui lòng nhập danh sách người nhận");
                return;
            }
            var content = $("#MailEditor_ifr").contents().find("#tinymce").html();
            for (var i = 0; i < 400; i++) {
                content = content.replace('"', "'");
            }
            $.ajax({
                async: false,
                dataType: 'json',
                url: "/api/users/user.ashx",
                type: 'POST',
                data: {
                    action: "sendMail",
                    title: $("#txtTitle").val(),
                    content: content,
                    users: $("#ListEmail").val()
                },
                success: function(data) {
                    if (data.result == "1") {
                        jAlert("Việc gửi mail đang được thực hiện");
                    }
                    else if (data.result == "2") {
                        jAlert("Một số thành viên bị sai thông tin: " + data.failed);
                    }
                }
            });
        }
        else {
            if ($("#FileEmail").val() == "") {
                jAlert("Vui lòng chọn file chứa thông tin thành viên");
                return;
            }
            var content = $("#MailEditor_ifr").contents().find("#tinymce").html();
            content = content.replace(/</g, "|lt");
            content = content.replace(/>/g, "|gt");

            var refesh = new Date();
            $("#txtContent").val(content);
            $("#aspnetForm").attr("action", "/api/users/user.ashx?" + refesh.getMilliseconds());
            $("#aspnetForm").attr("method", "post");
            $("#aspnetForm").attr("target", "UploadWindow");
            $("#aspnetForm").attr("enctype", "multipart/form-data");
            $("#aspnetForm").attr("encoding", "multipart/form-data");
            $("#action-request").attr("name", "action");
            $("#aspnetForm").submit();
        }
    });

    SendMailSuccess = function(result) {
        if (result == "2") {
            jAlert("File đầu vào phải là *.txt");
            return;
        }
        if (result == "1") {
            jAlert("Việc gửi mail đang được thực hiện");
            return;
        }
    }

    /*** end: Send Mail ***/
});